import {Button, Col, Divider, Row,Alert} from "antd";
import React from "react";
import EditTable from "../../../components/EditTable";
import {UnControlled as CodeMirror} from 'react-codemirror2'
import 'codemirror/lib/codemirror.js'
import 'codemirror/lib/codemirror.css';
// 主题风格
import 'codemirror/theme/solarized.css';
// 代码模式，clike是包含java,c++等模式的
import 'codemirror/mode/properties/properties';
import 'codemirror/mode/css/css';
//代码高亮
import 'codemirror/addon/selection/active-line';
//搜索代码
import 'codemirror/addon/search/matchesonscrollbar.js';
import 'codemirror/addon/search/match-highlighter.js';
import 'codemirror/addon/search/jump-to-line.js';
import 'codemirror/addon/dialog/dialog.js';
import 'codemirror/addon/dialog/dialog.css';
import 'codemirror/addon/search/searchcursor.js';
import 'codemirror/addon/search/search.js';

import http from "../../../utils/request";

const lineSplit = ": ";

export default class extends React.Component {

  state = {
    form: {
      ports: [],
      binds: [],
      environment: [],
      netWork: "",
      ipAddress: ""
    },
    data: '',
    isChange: false
  }

  constructor(props) {
    super(props);

    let config = this.props.app.config;
    if (config) {
      this.state.form = config
    }
    this.state.data = this.state.form.environment
  }


  portsColumns = [
    {title: '主机端口', dataIndex: 'publicPort', dataType: 'InputNumber'},
    {title: '容器端口', dataIndex: 'privatePort', dataType: 'InputNumber'},
    {title: '协议', dataIndex: 'protocol', dataType: 'Select', valueEnum: {TCP: 'TCP', UDP: 'UDP'}},
  ]

  bindsColumns = [
    {title: '主机路径', dataIndex: 'publicVolume', dataType: 'Input'},
    {title: '容器路径', dataIndex: 'privateVolume', dataType: 'Input'},
    {title: '只读', dataIndex: 'readOnly', dataType: 'Select', valueEnum: {true: '只读', false: '读写'}},
  ]

  envColumns = [
    {title: '键', dataIndex: 'key', dataType: 'Input'},
    {title: '值', dataIndex: 'value', dataType: 'Input'},
  ]

  update = () => {
    const {form} = this.state;
    form.environment = this.buildConfigList(this.state.data)
    console.log(form)
    http.post('/api/app/updateConfig?id=' + this.props.app.id, form)
  }

  renderToText(value) {
    if (!value || value.length === 0) {
      return "";
    }
    let text = "";

    value.map(d => {
      text += d.key + lineSplit + d.value + "\n"
    })
    return text;
  }

  buildConfigList(value) {
    //没有做变更
    if (!this.state.isChange) {
      return value;
    }

    if (!value) {
      return [];
    }
    let split = value.split("\n");

    let resultList = [];
    split.map(d => {
      //获取key
      //获取value
      let lineData = d.split(lineSplit);
      let key = lineData[0];
      let value = lineData[1];
      let conf = {
        key: '',
        value: ''
      }
      if (key && value) {
        conf.key = key
        conf.value = value
        resultList.push(conf)
      }
    })
    return resultList
  }


  render() {
    const {form} = this.state;
    const {data, isChange} = this.state
    let that = this
    return <div>

      <Row>
        <Col flex="auto">
          网卡名称：<input value={form.netWork} onChange={e => this.setState({form: {...form, netWork: e.target.value}})}/>
        </Col>
        <Col flex="auto">
          IP地址：<input value={form.ipAddress}
                      onChange={e => this.setState({form: {...form, ipAddress: e.target.value}})}/>
        </Col>
      </Row>
      <Divider/>

      <Row>
        <Col flex="100px">
          <h4>端口绑定</h4>
        </Col>
        <Col flex="auto">
          <EditTable columns={this.portsColumns} dataSource={form.ports} onChange={(data => {
            this.setState({form: {...form, ports: data}})
          })}/>
        </Col>
      </Row>
      <Divider/>

      <Row>
        <Col flex="100px">
          <h4>卷映射</h4>
        </Col>
        <Col flex="auto">
          <EditTable columns={this.bindsColumns} dataSource={form.binds} onChange={(data => {
            this.setState({form: {...form, binds: data}})
          })}/>
        </Col>
      </Row>
      <Divider/>

      <Row>
        <Col flex="100px">
          <h4>环境变量</h4>
        </Col>
        {/*<Col flex="auto">*/}
        {/*  <EditTable columns={this.envColumns} dataSource={form.environment} onChange={(data => {*/}
        {/*    this.setState({form: {...form, environment: data}})*/}
        {/*  })}/>*/}
        {/*</Col>*/}
        <Col flex="auto">
          <Row>
            <Col flex="auto"> <Button type="primary" onClick={() => {
              this.instance.execCommand('findPersistent');
            }}>搜索</Button>
            </Col>
            <Col flex="auto"><Alert message={"中间分割以 ': ' 为分割符号,冒号和空格，不要少打！！！"} type="info"/></Col>
          </Row>
          <CodeMirror
            editorDidMount={editor => {
              this.instance = editor
            }}
            value={this.renderToText(form.environment)}
            options={{
              mode: {name: 'text/x-properties'},
              // theme: 'solarized dark',
              autofocus: true,//自动获取焦点
              styleActiveLine: true,//光标代码高亮
              lineNumbers: true, //显示行号
              smartIndent: true,  //自动缩进
              //start-设置支持代码折叠
              lineWrapping: false,
              foldGutter: true,
              gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],//end
              extraKeys: {
                "Ctrl-Z": function (editor) {
                  editor.undo();
                }
              },
              matchBrackets: true,  //括号匹配，光标旁边的括号都高亮显示
              autoCloseBrackets: true //键入时将自动关闭()[]{}''""
            }}
            onChange={((editor, data1, value) => {
              this.setState({isChange: true})
              this.setState({data: value})
            })}

            // 在失去焦点的时候触发，这个时候放数据最好
            // onBlur={((editor, data1, value) => {
            //   console.log(value)
            // })}

            // // 这个必须加上，否则在一些情况下，第二次打开就会有问题
            // //     onBeforeChange={(editor, data, value) => {
            // //       console.log("onBeforeChange fresh")
            // //       console.log(JSON.stringify(data));
            // //     }}
            //     /* HERE: pick out only the value. and might as well get name. */
          />
        </Col>
      </Row>


      <Divider/>

      <Row>
        <Col flex="100px">
        </Col>
        <Col flex="auto">
          <Button type="primary" onClick={this.update}>保存更改</Button>
        </Col>
      </Row>


    </div>

  }
}
